package com.android.lib.base.manager

import com.blankj.utilcode.util.GsonUtils
import com.google.gson.reflect.TypeToken
import com.tencent.mmkv.MMKV
import com.tencent.mmkv.MMKVLogLevel
import com.android.lib.base.baseclass.BaseApplication

object MMKVManager {

    fun mmkvInit() {
        MMKV.initialize(BaseApplication.getContext())
        MMKV.setLogLevel(
            if (com.android.lib.base.BuildConfig.DEBUG) {
                MMKVLogLevel.LevelDebug
            } else {
                MMKVLogLevel.LevelError
            }
        )
    }

    fun encodeString(key: String, value: String) {
        MMKV.defaultMMKV().encode(key, value)
    }

    fun encodeInt(key: String, value: Int) {
        MMKV.defaultMMKV().encode(key, value)
    }

    fun encodeBoolean(key: String, value: Boolean) {
        MMKV.defaultMMKV().encode(key, value)
    }

    fun <T> encodeList(key: String, value: MutableList<T>) {
        MMKV.defaultMMKV().encode(key, GsonUtils.toJson(value))
    }

    fun <T> encodeBean(key: String, bean: T) {
        MMKV.defaultMMKV().encode(key, GsonUtils.toJson(bean))
    }

    fun decodeString(key: String, defaultValue: String = ""): String {
        MMKV.defaultMMKV().decodeString(key, defaultValue)?.let {
            return it
        }
        return ""
    }

    fun decodeInt(key: String, defaultValue: Int = 0): Int {
        return MMKV.defaultMMKV().decodeInt(key, defaultValue)
    }

    fun decodeBoolean(key: String, defaultValue: Boolean = false): Boolean {
        return MMKV.defaultMMKV().decodeBool(key, defaultValue)
    }


    fun <T> decodeList(key: String): ArrayList<T> {
        try {
            MMKV.defaultMMKV().decodeString(key, null).let {
                return GsonUtils.fromJson(
                    it,
                    object : TypeToken<ArrayList<T>>() {}.type
                )
            }
        }catch (e:Exception){
            e.printStackTrace()
        }
        return ArrayList()
    }

    fun <T> decodeBean(key: String, type: Class<T>): T? {
        try {
            MMKV.defaultMMKV().decodeString(key, null).let {
                return GsonUtils.fromJson(it, type)
            }
        }catch (e:Exception){
            e.printStackTrace()
        }
        return null
    }


}

data class TestBean(
    val test: String
)